package service

import (
	"context"
	"fmt"
	"math/rand"
	"time"
	"user-service/basic/global"
	__ "user-service/basic/proto"
	"user-service/pkg"
)

type SendSMSService struct {
	__.UnimplementedSendSmsServer
}

func (s *SendSMSService) SendSms(_ context.Context, req *__.SendSmsReq) (resp *__.SendSmsResp, err error) {

	//mobile := req.Mobile
	//
	//if mobile == "" {
	//	return nil, fmt.Errorf("手机号不允许为空，请填写手机号")
	//}
	//
	//code := fmt.Sprintf("%06d", rand.Intn(1000000))
	//
	//limitKey := "SendSmsNumber" + mobile
	//codeKey := "SendSmsCode" + mobile
	//
	//count, _ := global.Rdb.Get(global.Ctx, limitKey).Int()
	//if count >= 3 {
	//	return nil, fmt.Errorf("5分钟内发送大于3次，过于频繁，请稍后再试")
	//}
	//
	//result, err := global.Rdb.Exists(global.Ctx, codeKey).Result()
	//if err != nil {
	//	return nil, fmt.Errorf("redis检查失败: %v", err)
	//}
	//
	//if result > 0 {
	//	return nil, fmt.Errorf("验证码仍在有效期内，请勿重复发送")
	//}

	//	err = global.Rdb.Set(global.Ctx, codeKey, code, time.Minute*10).Err()
	//	if err != nil {
	//		return nil, fmt.Errorf("redis写入失败: %v", err)
	//	}
	//
	//	pipe := global.Rdb.TxPipeline()
	//	pipe.Incr(global.Ctx, limitKey)
	//
	//	if count == 0 {
	//		pipe.Expire(global.Ctx, limitKey, time.Minute*5)
	//	}
	//
	//	_, _ = pipe.Exec(global.Ctx)
	//
	//	rabbitmq := pkg.NewRabbitMQSimple("sendSms")
	//	msg := map[string]string{
	//		"mobile": mobile,
	//		"code":   code,
	//	}
	//	date, _ := json.Marshal(msg)
	//	rabbitmq.PublishSimple(string(date))
	//
	//	resp = &__.SendSmsResp{
	//		Message: "验证码发送中，请稍后查收",
	//	}
	//
	//	return resp, err
	mobile := req.Mobile

	if mobile == "" {
		return nil, fmt.Errorf("手机号不许为空")
	}
	code := fmt.Sprintf("%06d", rand.Intn(1000000))
	codeKey := "sendSms" + mobile
	limitKey := "sendSmsLimit" + mobile

	count, _ := global.Rdb.Get(global.Ctx, limitKey).Int()

	if count >= 3 {
		return nil, fmt.Errorf("<UNK>")
	}

	result, err := global.Rdb.Exists(global.Ctx, codeKey).Result()
	if err != nil {
		return nil, err
	}

	if result > 0 {
		return nil, fmt.Errorf("<UNK>")
	}

	err = global.Rdb.Set(global.Ctx, codeKey, code, time.Minute*10).Err()
	if err != nil {
		return nil, err
	}

	pipe := global.Rdb.TxPipeline()
	pipe.Incr(global.Ctx, codeKey)

	if count == 0 {
		pipe.Expire(global.Ctx, codeKey, 5*time.Minute)
	}

	pipe.Exec(global.Ctx)

	pkg.SendSms(mobile, code)

	return nil, err
}
